package dto;

import java.io.IOException;
import java.io.OutputStream;

/**
 * 封装响应对象
 *
 * 基于HTTP协议的格式进行输出写入。
 */
public class MyResponse {

    private OutputStream outputStream;

    public MyResponse(OutputStream outputStream){
        this.outputStream = outputStream;
    }

    public void write(String context) throws IOException {

        // 一个典型的http  response header
        /**
         * HTTP/1.1 200 OK
         Cache-Control: private
         Connection: keep-alive
         Content-Encoding: gzip
         Content-Type: text/html;charset=utf-8
         Date: Sat, 26 Jun 2021 06:40:01 GMT
         Expires: Sat, 26 Jun 2021 06:40:01 GMT
         Server: BWS/1.0
         Vary: Accept-Encoding
         Content-Length: 78
         */

        // http response body
        /**
         *
         {"errNo":"0","data": { "redDot": [  ], "newWord": [  ], "layer": [  ] }}
         */

        StringBuilder httpResponse = new StringBuilder();
        httpResponse.append("HTTP/1.1 200 OK").append("\n")
                .append("Content-Type: text/html;charset=utf-8").append("\n")
                .append("\r\n")
                .append("<html><body>")
                .append(context)
                .append("</html></body>");

        outputStream.write(httpResponse.toString().getBytes());
        outputStream.close();
    }


}
